package com.qiniuyun.backai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiniuyun.backai.common.PageResult;
import com.qiniuyun.backai.domain.po.Character;
import com.qiniuyun.backai.domain.po.Conversation;
import com.qiniuyun.backai.domain.vo.ConversationHistoryVO;
import com.qiniuyun.backai.domain.vo.MessageVO;
import com.qiniuyun.backai.mapper.CharacterMapper;
import com.qiniuyun.backai.mapper.ConversationMapper;
import com.qiniuyun.backai.model.pojo.Chat;
import com.qiniuyun.backai.service.ChatService;
import com.qiniuyun.backai.service.IConversationService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 会话服务实现类
 * @author 王程楠
 * @since 2025-09-23
 */
@Service
@RequiredArgsConstructor
public class IConversationServiceImpl extends ServiceImpl<ConversationMapper, Conversation> implements IConversationService {

    private final CharacterMapper characterMapper;
    private final ChatService chatService;

    @Override
    @Transactional(readOnly = true)
    public PageResult<ConversationHistoryVO> getHistorySessions(Integer page, Integer size, Long userId) {
        // 创建分页对象
        Page<Conversation> pageParam = new Page<>(page, size);
        
        // 构建查询条件
        LambdaQueryWrapper<Conversation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Conversation::getIsDeleted, 0)
                .orderByDesc(Conversation::getUpdatedAt);
        
        // 如果指定了用户ID，则按用户ID过滤
        if (userId != null) {
            queryWrapper.eq(Conversation::getUserId, userId);
        }
        
        // 执行分页查询
        IPage<Conversation> pageResult = this.page(pageParam, queryWrapper);
        
        // 获取所有角色ID
        List<Long> charIds = pageResult.getRecords().stream()
                .map(Conversation::getCharId)
                .distinct()
                .collect(Collectors.toList());

        // 批量查询角色信息
        Map<Long, Character> characterMap = charIds.isEmpty() ?
                Collections.emptyMap() :
                characterMapper.selectBatchIds(charIds)
                        .stream()
                        .collect(Collectors.toMap(Character::getCharId, character -> character));

        // 转换为VO
        List<ConversationHistoryVO> voList = pageResult.getRecords().stream()
                .map(conversation -> convertToHistoryVO(conversation, characterMap))
                .collect(Collectors.toList());

        return new PageResult<>(voList, page, size, pageResult.getTotal());

    }

    @Override
    @Transactional(readOnly = true)
    public List<MessageVO> getSessionMessages(Long convId) {
        // 通过ChatService查询消息列表
        LambdaQueryWrapper<Chat> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Chat::getConvid, convId)
                .eq(Chat::getIsdelete, 0)
                .orderByAsc(Chat::getCreatetime);
        
        List<Chat> chatList = chatService.list(queryWrapper);
        
        // 转换为MessageVO
        return chatList.stream()
                .map(this::convertToMessageVO)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public boolean deleteSession(Long convId) {
        // 逻辑删除会话
        Conversation conversation = this.getById(convId);
        if (conversation == null) {
            return false;
        }
        
        conversation.setIsDeleted(true);
        boolean conversationDeleted = this.updateById(conversation);
        
        // 同时删除相关的消息记录
        boolean messagesDeleted = chatService.deleteByConvId(String.valueOf(convId)) > 0;
        
        return conversationDeleted;
    }

    /**
     * 转换为历史会话VO
     */
    private ConversationHistoryVO convertToHistoryVO(Conversation conversation, Map<Long, Character> characterMap) {
        ConversationHistoryVO vo = new ConversationHistoryVO();
        vo.setConvId(conversation.getConvId());
        vo.setCharId(conversation.getCharId());
        vo.setTitle(conversation.getTitle());
        
        // 设置角色信息
        Character character = characterMap.get(conversation.getCharId());
        if (character != null) {
            vo.setCharacterName(character.getName());
            vo.setCharacterAvatar(character.getAvatarUrl());
        }
        
        // 查询消息数量
        LambdaQueryWrapper<Chat> chatQueryWrapper = new LambdaQueryWrapper<>();
        chatQueryWrapper.eq(Chat::getConvid, conversation.getConvId())
                .eq(Chat::getIsdelete, 0);
        long messageCount = chatService.count(chatQueryWrapper);
        vo.setMessageCount((int) messageCount);
        
        return vo;
    }

    /**
     * 转换为消息VO
     */
    private MessageVO convertToMessageVO(Chat chat) {
        MessageVO vo = new MessageVO();
        vo.setMsgId(chat.getId());
        vo.setConvId(chat.getConvid());
        
        // 角色类型转换
        vo.setRole(chat.getRole() == 0 ? "USER" : "ASSISTANT");
        
        // 内容类型转换
        vo.setContentType(chat.getContenttype() == 0 ? "TEXT" : "AUDIO");
        
        // 内容处理
        if (chat.getContent() != null) {
            vo.setContent(chat.getContent().toString());
        }
        
        vo.setAudioUrl(chat.getAudiourl());
        
        return vo;
    }
}
